package com.dgut.edu.cn.design.mode.filterchain;

import com.dgut.edu.cn.design.mode.filterchain.dto.RuleFilterResVo;
import com.dgut.edu.cn.design.mode.filterchain.filter.RuleFilter;
import com.dgut.edu.cn.design.mode.filterchain.handler.PriceCompareHandle;
import com.dgut.edu.cn.design.mode.log.LogMsgKit;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @description: 每个业务具体拿到业务过滤链结果
 * @author: hongbin.zheng
 * @create: 2023-08-11 10:29
 **/
@Slf4j
@Data
public class FilterChain<T> {
	private String name;
	private List<PriceCompareHandle<T>> priceCompareHandleList;
	private List<RuleFilter<T>> ruleFilterList;

	public FilterChain() {

	}

	public FilterChain(String name) {
		this.name = name;
		this.priceCompareHandleList = Lists.newArrayList();
		this.ruleFilterList = Lists.newArrayList();
	}

	public FilterChain(String name, List<PriceCompareHandle<T>> priceCompareHandleList,
			List<RuleFilter<T>> ruleFilterList) {
		this.name = name;
		this.priceCompareHandleList = priceCompareHandleList;
		this.ruleFilterList = ruleFilterList;
	}


	public T process(T entity) throws Exception {
		if (ruleFilterList.size() > 0) {
			for (RuleFilter<T> ruleFilter : ruleFilterList) {
				RuleFilterResVo ruleFilterResVo = ruleFilter.doFilter(entity);
				if (ruleFilterResVo.isFilter()) {
					log.info(LogMsgKit.of("FilterChain_process").p("filterName", ruleFilterResVo.getRuleFilterName())
							.p("entity", entity).p("triggerRule", ruleFilterResVo.getMsg()).end("没有通过该过滤器"));
					return null;
				}
			}
			// 能达到这一步的都是 符合业务的数据，执行业务操作
		}
		if (priceCompareHandleList.size() > 0) {
			for (PriceCompareHandle<T> handle : priceCompareHandleList) {
				handle.handler(entity);
			}
		}
		return entity;
	}


}
